import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // 登录页面
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/Login.vue'),
      meta: { 
        requiresAuth: false,
        title: '登录'
      }
    },
    
    // 主应用布局
    {
      path: '/',
      component: () => import('@/components/Layout/MainLayout.vue'),
      meta: { requiresAuth: true },
      redirect: '/dashboard',
      children: [
        // 个人中心/仪表板
        {
          path: 'dashboard',
          name: 'Dashboard',
          component: () => import('@/views/Dashboard.vue'),
          meta: { 
            title: '个人中心',
            roles: ['super_admin', 'campus_admin', 'student', 'coach']
          }
        },

        // 校区管理 (超级管理员)
        {
          path: 'campus',
          meta: { 
            title: '校区管理',
            roles: ['super_admin']
          },
          children: [
            {
              path: 'list',
              name: 'CampusList',
              component: () => import('@/views/Campus/CampusList.vue'),
              meta: { 
                title: '校区列表',
                roles: ['super_admin']
              }
            },
            {
              path: 'create',
              name: 'CampusCreate',
              component: () => import('@/views/Campus/CampusCreate.vue'),
              meta: { 
                title: '新建校区',
                roles: ['super_admin']
              }
            }
          ]
        },

        // 用户管理
        {
          path: 'users',
          meta: { 
            title: '用户管理',
            roles: ['super_admin', 'campus_admin', 'student', 'coach']
          },
          children: [
            // 学员管理 (校区管理员)
            {
              path: 'students',
              name: 'StudentManagement',
              component: () => import('@/views/Users/StudentManagement.vue'),
              meta: { 
                title: '学员管理',
                roles: ['campus_admin']
              }
            },
            // 教练管理 (校区管理员)
            {
              path: 'coaches',
              name: 'CoachManagement',
              component: () => import('@/views/Users/CoachManagement.vue'),
              meta: { 
                title: '教练管理',
                roles: ['campus_admin']
              }
            },
            // 我的学员 (教练)
            {
              path: 'my-students',
              name: 'MyStudents',
              component: () => import('@/views/Users/MyStudents.vue'),
              meta: { 
                title: '我的学员',
                roles: ['coach']
              }
            },
            // 我的教练 (学员)
            {
              path: 'my-coaches',
              name: 'MyCoaches',
              component: () => import('@/views/Users/MyCoaches.vue'),
              meta: { 
                title: '我的教练',
                roles: ['student']
              }
            }
          ]
        },

        // 教练中心 (学员)
        {
          path: 'coaches',
          meta: { 
            title: '教练中心',
            roles: ['student']
          },
          children: [
            {
              path: 'search',
              name: 'CoachSearch',
              component: () => import('@/views/Coaches/CoachSearch.vue'),
              meta: { 
                title: '查找教练',
                roles: ['student']
              }
            },
            {
              path: 'pairing',
              name: 'CoachPairing',
              component: () => import('@/views/Coaches/CoachPairing.vue'),
              meta: { 
                title: '双选管理',
                roles: ['student']
              }
            }
          ]
        },

        // 课程预约
        {
          path: 'booking',
          meta: { 
            title: '课程预约',
            roles: ['student', 'coach', 'campus_admin']
          },
          children: [
            {
              path: 'calendar',
              name: 'BookingCalendar',
              component: () => import('@/views/Booking/BookingCalendar.vue'),
              meta: { 
                title: '课表日历',
                roles: ['student', 'coach', 'campus_admin']
              }
            },
            {
              path: 'manage',
              name: 'BookingManagement',
              component: () => import('@/views/Booking/BookingManagement.vue'),
              meta: { 
                title: '预约管理',
                roles: ['campus_admin']
              }
            },
            {
              path: 'my-schedule',
              name: 'MySchedule',
              component: () => import('@/views/Booking/MySchedule.vue'),
              meta: { 
                title: '我的课程',
                roles: ['student', 'coach']
              }
            }
          ]
        },

        // 训练评价
        {
          path: 'reviews',
          name: 'Reviews',
          component: () => import('@/views/Reviews.vue'),
          meta: { 
            title: '训练评价',
            roles: ['student', 'coach']
          }
        },

        // 比赛管理
        {
          path: 'competition',
          meta: { 
            title: '比赛管理',
            roles: ['student', 'campus_admin']
          },
          children: [
            {
              path: 'enroll',
              name: 'CompetitionEnroll',
              component: () => import('@/views/Competition/CompetitionEnroll.vue'),
              meta: { 
                title: '月赛报名',
                roles: ['student']
              }
            },
            {
              path: 'schedule',
              name: 'CompetitionSchedule',
              component: () => import('@/views/Competition/CompetitionSchedule.vue'),
              meta: { 
                title: '赛程查询',
                roles: ['student']
              }
            },
            {
              path: 'manage',
              name: 'CompetitionManagement',
              component: () => import('@/views/Competition/CompetitionManagement.vue'),
              meta: { 
                title: '月赛管理',
                roles: ['campus_admin']
              }
            }
          ]
        },

        // 财务中心
        {
          path: 'finance',
          meta: { 
            title: '财务中心',
            roles: ['student', 'coach', 'campus_admin', 'super_admin']
          },
          children: [
            {
              path: 'recharge',
              name: 'FinanceRecharge',
              component: () => import('@/views/Finance/FinanceRecharge.vue'),
              meta: { 
                title: '余额充值',
                roles: ['student']
              }
            },
            {
              path: 'records',
              name: 'FinanceRecords',
              component: () => import('@/views/Finance/FinanceRecords.vue'),
              meta: { 
                title: '交易记录',
                roles: ['student', 'coach']
              }
            },
            {
              path: 'earnings',
              name: 'FinanceEarnings',
              component: () => import('@/views/Finance/FinanceEarnings.vue'),
              meta: { 
                title: '收入统计',
                roles: ['coach']
              }
            },
            {
              path: 'manage',
              name: 'FinanceManagement',
              component: () => import('@/views/Finance/FinanceManagement.vue'),
              meta: { 
                title: '财务管理',
                roles: ['campus_admin']
              }
            },
            {
              path: 'overview',
              name: 'FinanceOverview',
              component: () => import('@/views/Finance/FinanceOverview.vue'),
              meta: { 
                title: '财务概览',
                roles: ['super_admin']
              }
            }
          ]
        },

        // 系统管理
        {
          path: 'system',
          meta: { 
            title: '系统管理',
            roles: ['campus_admin', 'super_admin']
          },
          children: [
            {
              path: 'messages',
              name: 'SystemMessages',
              component: () => import('@/views/System/SystemMessages.vue'),
              meta: { 
                title: '消息中心',
                roles: ['campus_admin', 'super_admin', 'student', 'coach']
              }
            },
            {
              path: 'logs',
              name: 'SystemLogs',
              component: () => import('@/views/System/SystemLogs.vue'),
              meta: { 
                title: '系统日志',
                roles: ['campus_admin', 'super_admin']
              }
            }
          ]
        },

        // 许可管理 (超级管理员)
        {
          path: 'license',
          name: 'LicenseManagement',
          component: () => import('@/views/LicenseManagement.vue'),
          meta: { 
            title: '许可管理',
            roles: ['super_admin']
          }
        },

        // 个人资料
        {
          path: 'profile',
          name: 'Profile',
          component: () => import('@/views/Profile.vue'),
          meta: { 
            title: '个人资料',
            roles: ['super_admin', 'campus_admin', 'student', 'coach']
          }
        },

        // 系统设置
        {
          path: 'settings',
          name: 'Settings',
          component: () => import('@/views/Settings.vue'),
          meta: { 
            title: '系统设置',
            roles: ['super_admin', 'campus_admin', 'student', 'coach']
          }
        }
      ]
    },

    // 404 页面
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import('@/views/NotFound.vue'),
      meta: { 
        title: '页面未找到'
      }
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  // 恢复用户状态
  if (!userStore.isLoggedIn) {
    userStore.restoreFromStorage()
  }

  // 检查是否需要登录
  if (to.meta.requiresAuth && !userStore.isLoggedIn) {
    next('/login')
    return
  }

  // 如果已登录且访问登录页，重定向到首页
  if (to.path === '/login' && userStore.isLoggedIn) {
    next('/dashboard')
    return
  }

  // 检查角色权限
  if (to.meta.roles && Array.isArray(to.meta.roles)) {
    if (!userStore.hasRole(to.meta.roles)) {
      // 无权限，重定向到首页
      next('/dashboard')
      return
    }
  }

  next()
})

export default router
